package com.atguigu.spzx.manager.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.spzx.manager.mapper.SysUserMapper;
import com.atguigu.spzx.manager.service.SysUserService;
import com.atguigu.spzx.model.dto.system.LoginDto;
import com.atguigu.spzx.model.dto.system.SysUserDto;
import com.atguigu.spzx.model.entity.system.SysUser;
import com.atguigu.spzx.model.exception.GuiguException;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import com.atguigu.spzx.model.vo.system.LoginVo;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;


import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author LT
 * @create 2024-03-07-10:15
 */
@Service
public class SysUserServiceImpl implements SysUserService {

    @Resource
    SysUserMapper sysUserMapper;

    @Autowired
    StringRedisTemplate redisTemplate;


    @Override
    public LoginVo login(LoginDto loginDto) {

        //获取前端输入的验证码
        String codeKey = loginDto.getCodeKey();
        String code = loginDto.getCode();
        //根据用户名查询用户
        SysUser sysUser = sysUserMapper.selectByUserName(loginDto);
        if (sysUser==null){
            throw new GuiguException(ResultCodeEnum.LOGIN_USERNAME_ERROR,null);
        }
        //验证密码是否正确
        String inputPassWord = loginDto.getPassword();
        //System.out.println(inputPassWord);
        String md5InputPassWord = DigestUtils.md5DigestAsHex(inputPassWord.getBytes());
        //System.out.println(md5InputPassWord);
        //System.out.println(sysUser.getPassword());
        if (!md5InputPassWord.equals(sysUser.getPassword())){
            throw new GuiguException(ResultCodeEnum.LOGIN_ERROR,null);
        }
        //判断用户是否被禁用
        if (1!=sysUser.getStatus()){
            throw new GuiguException(ResultCodeEnum.LOGIN_DISABLED_ERROR);
        }

        //校验验证码是否正确
        String redisCode = redisTemplate.opsForValue().get("user:login:validatecode:" + codeKey);
        if (StringUtils.isEmpty(redisCode) || !StringUtils.equalsIgnoreCase(redisCode,code)){
            throw new GuiguException(ResultCodeEnum.VALIDATE_COOE_ERROR);
        }

        redisTemplate.delete("user:login:validatecode:" + codeKey);

        //生成令牌，保存数据到Redis中
        String token = UUID.randomUUID().toString().replace("-", "");
        sysUser.setPassword(null);
        redisTemplate.opsForValue().set("user:login:"+token, JSON.toJSONString(sysUser),600, TimeUnit.MINUTES);
        //构建响应结果
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        loginVo.setRefresh_token("1");
        //返回
        return loginVo;
    }

    @Override
    public SysUser getUserInfo(String token) {
        String sysUserJson = redisTemplate.opsForValue().get("user:login:" + token);
        SysUser sysUser = JSON.parseObject(sysUserJson, SysUser.class);
        return sysUser;
    }

    @Override
    public void logout(String token) {
        redisTemplate.delete("user:login:" + token);
    }

    @Override
    public PageInfo<SysUser> findDtoPage(Integer pageNum, Integer pageSize, SysUserDto sysUserDto) {
        PageHelper.startPage(pageNum,pageSize);
        List<SysUser> list = sysUserMapper.findDtoPage(sysUserDto);
        return new PageInfo<>(list);
    }

    @Override
    public SysUser findSysUserById(Long id) {
       SysUser sysUser  = sysUserMapper.findSysUserById(id);
        sysUser.setPassword(null);
        return sysUser;
    }

    @Override
    public void saveSysUser(SysUser sysUser) {
        String password = sysUser.getPassword();
        String passwordMd5 = DigestUtils.md5DigestAsHex(password.getBytes());
        sysUser.setPassword(passwordMd5);
        sysUserMapper.saveSysUser(sysUser);
    }

    @Override
    public List<SysUser> findAll() {
        List<SysUser> userList = sysUserMapper.findAll();
        return userList;
    }

    @Override
    public void UpdateById(SysUser sysUser) {
        sysUserMapper.UpdateById(sysUser);
    }

    @Override
    public void deleteById(Long id) {
        sysUserMapper.deleteById(id);
    }
}
